package com.es.www.transaction.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Objects;

/**
 * @Created by michangtao
 * @Date 2022/2/9 15:49
 * @Description
 */
public class JdbcUtil {

    public static final String JDBC_URL = "jdbc:mysql://192.168.63.72:3306/silk_bridge?useUnicode=true&characterEncoding=utf-8&serverTimezone=CTT&allowMultiQueries=true";

    public static ThreadLocal<Connection> cThreadLocal = new ThreadLocal<>();

    public static Connection openConnection(){
        Connection connection;
        try{
            connection = DriverManager.getConnection(JDBC_URL, "root", "123456");
            cThreadLocal.set(connection);
        }catch (SQLException e){
            cThreadLocal.remove();
            throw new RuntimeException(e);
        }
        return connection;
    }

    public static Connection getConnection(){
        if(Objects.nonNull(cThreadLocal.get())){
            return cThreadLocal.get();
        }
        return openConnection();
    }

    public static void removeConnection() {
        cThreadLocal.remove();
    }
}
